import axios from "axios";
import crypto from "crypto";


/**
 * 生成钉钉签名（如果设置了密钥）
 */
function getSign(secret) {
    if (!secret) return "";
    const timestamp = Date.now();
    const stringToSign = `${timestamp}\n${secret}`;
    const sign = crypto
        .createHmac("sha256", secret)
        .update(stringToSign)
        .digest("base64");
    return `&timestamp=${timestamp}&sign=${encodeURIComponent(sign)}`;
}

/**
 * 发送群 ActionCard 消息
 */
export async function sendGroupCard(secret, webhook) {
    try {
        let url = webhook;
        if (secret) url += getSign(secret);

        const payload = {
            msgtype: "actionCard",
            actionCard: {
                title: "抖音直播数据汇总",
                text: `直播数据汇总已更新\n\n ![图片](https://golf-lives.com/zhiboCard.png)`,
                btnOrientation: "1",
                btns: [
                    {
                        title: "📊 查看完整内容",
                        actionURL:
                            "dingtalk://dingtalkclient/action/openapp?corpid=ding58745046d80bf079ee0f45d8e4f7c288&container_type=work_platform&app_id=4045544333&redirect_type=jump&redirect_url=https%3A%2F%2Fdingding.link-hope.cn%2F",
                    }
                ],
            },
        };

        const res = await axios.post(url, payload);
        console.log("✅ 钉钉群消息发送成功：", res.data);
    } catch (err) {
        console.error("❌ 群消息发送失败：", err.message);
    }
}
